/**
 * 准备函数
 */
var operateRight = new Object();
$(document).ready(function() {
	
	// 加载权限
	loadRole();

	// 加载表格
	queryCoupon();

	// 绑定函数
	$("#queryButton").bind("click", confirmQueryCoupon);
	$("#createButton").bind("click", showCreateCouponDialog);
	$("#confirmCreateButton").bind("click", confirmCreateCoupon);
	$("#confirmModifyButton").bind("click", confirmModifyCoupon);
	$("#confirmDistributeButton").bind("click", confirmDistributeCoupon);
});

/**
 * 加载权限
 */
function loadRole() {
	operateRight.modifyRight = $("#modifyCoupon").val();
	operateRight.enableRight = $("#enableCoupon").val();
	operateRight.distributeRight = $("#distributeCoupon").val();
}

/**
 * 查询用户
 */
function queryCoupon(pageIndex, pageSize) {
	// 组装参数
	var data = {};
	var productType = $.trim($("#productType").val());
	if (productType != "") {
		data['productType'] = productType;
	}
	var isEnable = $.trim($("#isEnable").val());
	if (isEnable != "") {
		data['isEnable'] = isEnable;
	}
	
	// 设置分页参数
	setPageIndex(data, pageIndex, pageSize);
	
	// 调用接口
	var response = callInterface("post", "admin/queryCoupon", data, false);
	if (response.code == 0) {
		// 清空表格及分页
		$("#couponTable tr:not(:first)").remove();
		$("#pageDiv").html("");

		var count = response.data.totalCount;
		if (count == null || count == 0) {
			// 获取表格行数、列数
			var trs = $("#couponTable").find("tr").length;
			var cols = $("#couponTable").find("tr:first th");
			$('#couponTable').append("<tr><td colspan='" + cols.length + "'>无数据!</td></tr>");
			return false;
		}

		// 得到总页数
		var list = response.data.couponList;
		if (list != null && list.length > 0) {
			for ( var i in list) {
				var trHtml = "<tr>";
				trHtml += "<td align='center'>" + list[i].name + "</td>";
				trHtml += "<td align='center'>" + list[i].productTypeName + "</td>";
				trHtml += "<td align='center'>" + Utils.toFormatDecimal(list[i].fullAmount,2) + "</td>";
				trHtml += "<td align='center'>" + Utils.toFormatDecimal(list[i].reduceAmount,2) + "</td>";
				trHtml += "<td align='center'>" + handleEmptyStr(list[i].provideNumber) + "</td>";
				trHtml += "<td align='center'>" + handleEmptyStr(list[i].balanceNumber) + "</td>";
				trHtml += "<td align='center'>" + handleEmptyStr(list[i].validDays) + "</td>";
				if(operateRight.enableRight){
					trHtml += "<td align='center'><input id='coupon_status_"+list[i].id+"' class='ace ace-switch' type='checkbox' " + 
					(list[i].isEnable? 'checked': '')+" onclick='enableCoupon(" + list[i].id + ");' /> <span class='lbl'></span></td>";
				}else{
					trHtml += "<td align='center'>" + (list[i].isEnable? '启用':'禁用') + "</td>";
				}
				trHtml += "<td align='center'>" + (list[i].isPublic?'是':'否') + "</td>";
				trHtml += "<td align='center'>" + handleEmptyStr(list[i].createdTime) + "</td>";
				trHtml += "<td align='center'>" + handleEmptyStr(list[i].title) + "</td>";
				// 操作
				trHtml += "<td align='center' class='operationColumn'>";
				if (operateRight.modifyRight == 1) {
					trHtml += "<a href='javascript:void(0);' class='edit' onclick='showModifyCouponDialog(" + JSON.stringify(list[i]) + ");'>编辑</a>&nbsp;&nbsp;";
				}
				if (operateRight.distributeRight == 1 && list[i].isEnable) {
					trHtml += "<a href='javascript:void(0);' class='add' onclick='toDistributeCoupon(\"" + list[i].id + "\",\"" + list[i].validDays + "\");'>指定公司</a>";
				}
				trHtml += "</td>";
				trHtml += "</tr>";

				// 动态添加一行
				$('#couponTable').append(trHtml);
			}
		}

		// 调用分页
		layui.use(['laypage'], function() {
			var laypage = layui.laypage;
			laypage.render({
				elem : 'pageDiv',
				// pages : pages,
				curr : pageIndex || 1, // 当前页
				count : count,
				limit : pageSize,
				skip : true, // 是否开启跳页
				layout : ['count', 'prev', 'page', 'next', 'limit', 'skip'],
				groups : 5, // 连续显示分页数
				jump : function(obj, first) {
					if (!first) {
						queryCoupon(obj.curr, obj.limit);
					}
				}
			});
		});
	}else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 确认查询
 */
function confirmQueryCoupon() {
	queryCoupon();
}

/**
 * 设置启用禁用
 */
function enableCoupon(id) {
	var data = {};
	var isEnable = 0;
	if($('#coupon_status_'+id).is(":checked")){
		isEnable = 1;
	}
	data.id = id;
	data.isEnable = isEnable;
	
	// 调用接口
	var response = callInterface("post", "admin/enableCoupon", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
		// 刷新
		queryCoupon(currPage);
	} else {
		showErrorMsg(response.code, response.message);
	}
	return false;
}

/**
 * 显示创建对话框
 */
function showCreateCouponDialog() {
	// 弹出框
	$("#createCouponDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#addCouponForm')[0].reset();
	$("#cProductType").val("");
	$("#cIsPublic").prop('checked',false);
	updateLayuiForm();
}

/**
 * 确认创建
 */
function confirmCreateCoupon() {
	// 获取参数
	var data = {};
	
	var name = $.trim($("#cName").val());
	if (Utils.isNull(name)) {
		showAlert('代金券名称不能为空!');
		return;
	}
	data['name'] = name;
	
	var productType = $("#cProductType").val();
	if (Utils.isNull(productType)) {
		showAlert("请选择代金券类型!");
		return;
	}
	data['productType'] = productType;
	
	var fullAmount = $.trim($("#cFullAmount").val());
	if (Utils.isNull(fullAmount)) {
		showAlert("最低消费不能为空!");
		return false;
	}else if(fullAmount <=0){
		showAlert("最低消费应大于0!");
		return;
	}
	data['fullAmount'] = fullAmount;
	
	var reduceAmount = $("#cReduceAmount").val();
	if (Utils.isNull(reduceAmount)) {
		showAlert("减免金额不能为空!");
		return;
	}else if(reduceAmount <=0){
		showAlert("减免金额应大于0!");
		return;
	}else if(parseFloat(reduceAmount) >= parseFloat(fullAmount)){
		showAlert("减免金额应小于最低消费!");
		return;
	}
	data['reduceAmount'] = reduceAmount;
	
	var provideNumber = $("#cProvideNumber").val();
	if (Utils.isNull(provideNumber)) {
		showAlert("发放数量不能为空!");
		return;
	}else if(provideNumber <=0){
		showAlert("发放数量应大于0!");
		return;
	}
	data['provideNumber'] = provideNumber;
	
	var validDays = $.trim($("#cValidDays").val());
	if (Utils.isNull(validDays)) {
		showAlert("有效天数不能为空!");
		return false;
	}else if(validDays <=0){
		showAlert("有效天数应大于0天!");
		return;
	}
	data['validDays'] = validDays;
	
	var isPublic = $("#cIsPublic").is(":checked");
	data['isPublic'] = isPublic;
	
	var title = $.trim($("#cTitle").val());
	if (Utils.isNull(title)) {
		showAlert("使用说明不能为空!");
		return false;
	}
	data['title'] = title;
	
	// 调用接口
	var response = callInterface("post", "admin/createCoupon", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
		$('#createCouponDialog').modal("hide");

		// 刷新
		queryCoupon();
	}
	else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 显示修改用户对话框
 */
function showModifyCouponDialog(data) {
	// 显示对话框
	$("#modifyCouponDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#modifyCouponForm')[0].reset();
	
	// 设置参数
	$("#mId").val(data.id);
	$("#mName").val(data.name);
	$("#mProductType").val(data.productType);
	$("#mFullAmount").val(data.fullAmount);
	$("#mReduceAmount").val(data.reduceAmount);
	$("#mProvideNumber").val(data.provideNumber);
	$("#mValidDays").val(data.validDays);
	$("#mIsPublic").prop('checked',data.isPublic);;
	$("#mTitle").val(data.title);
	updateLayuiForm();
}

/**
 * 确认修改用户
 */
function confirmModifyCoupon() {
	
	// 获取参数
	var data = {};
	data['id'] = $.trim($("#mId").val());
	var name = $.trim($("#mName").val());
	if (Utils.isNull(name)) {
		showAlert('代金券名称不能为空!');
		return;
	}
	data['name'] = name;
	
	var productType = $("#mProductType").val();
	if (Utils.isNull(productType)) {
		showAlert("请选择代金券类型!");
		return;
	}
	data['productType'] = productType;
	
	var fullAmount = $.trim($("#mFullAmount").val());
	if (Utils.isNull(fullAmount)) {
		showAlert("最低消费不能为空!");
		return false;
	}else if(fullAmount <=0){
		showAlert("最低消费应大于0!");
		return;
	}else if(parseFloat(reduceAmount) >= parseFloat(fullAmount)){
		showAlert("减免金额应小于最低消费!");
		return;
	}
	data['fullAmount'] = fullAmount;
	
	var reduceAmount = $("#mReduceAmount").val();
	if (Utils.isNull(reduceAmount)) {
		showAlert("减免金额不能为空!");
		return;
	}else if(reduceAmount <=0){
		showAlert("减免金额应大于0!");
		return;
	}
	data['reduceAmount'] = reduceAmount;
	
	var provideNumber = $("#mProvideNumber").val();
	if (Utils.isNull(provideNumber)) {
		showAlert("发放数量不能为空!");
		return;
	}else if(provideNumber <=0){
		showAlert("发放数量应大于0天!");
		return;
	}
	data['provideNumber'] = provideNumber;
	
	var validDays = $.trim($("#mValidDays").val());
	if (Utils.isNull(validDays)) {
		showAlert("有效天数不能为空!");
		return false;
	}else if(validDays <=0){
		showAlert("有效天数应大于0!");
		return;
	}
	data['validDays'] = validDays;
	
	var isPublic = $("#mIsPublic").is(":checked");
	data['isPublic'] = isPublic;
	
	var title = $.trim($("#mTitle").val());
	if (Utils.isNull(title)) {
		showAlert("使用说明不能为空!");
		return false;
	}
	data['title'] = title;
	
	// 调用接口
	var response = callInterface("post", "admin/modifyCoupon", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
		$('#modifyCouponDialog').modal("hide");

		// 刷新
		queryCoupon(currPage);
	}
	else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 开始给公司分配代金券
 * 
 * @param couponId
 * @param days
 */
function toDistributeCoupon(couponId, days){
	// 显示对话框
	$("#distributeCouponDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#distributeCouponForm')[0].reset();
	
	// 设置参数
	$("#couponId").val(couponId);
	$("#days").val(days);
	$("#companyId").val("");
	updateLayuiForm();
}

/**
 * 给公司分配代金券
 */
function confirmDistributeCoupon() {
	var data = {};
	
	var couponId = $.trim($("#couponId").val());
	if (Utils.isNull(couponId)) {
		showAlert('系统异常，请联系管理员!');
		return;
	}
	data['couponId'] = couponId;
	
	var companyId = $.trim($("#companyId").val());
	if (Utils.isNull(companyId)) {
		showAlert('请选择公司!');
		return;
	}
	data['companyId'] = companyId;
	
	var days = $.trim($("#days").val());
	if (Utils.isNull(days)) {
		showAlert('请输入有效天数!');
		return;
	}else if(days <=0){
		showAlert("有效天数应大于0!");
		return;
	}
	data['days'] = days;

	// 调用接口
	var response = callInterface("post", "admin/distributeCoupon", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
		$('#distributeCouponDialog').modal("hide");

		// 刷新
		queryCoupon(currPage);
	}
	else {
		showErrorMsg(response.code, response.message);
	}
}